import { createRouter, createWebHistory } from 'vue-router'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    // 公共路由 - 无需登录即可访问
    {
      path: '/login',
      name: 'Login',
      component: () => import('../views/login/index.vue') // 修改为正确的登录组件路径
    },
    
    // 受保护的路由 - 需要登录才能访问
    {
      path: '/',
      name: 'Layout',
      component: () => import('../views/layout/index.vue'), // 布局组件
      meta: { requiresAuth: true },
      children: [
        {
          path: '', // 空路径表示默认子路由
          name: 'Home',
          redirect: '/main' // 默认重定向到/main
        },
        {
          path: 'main',
          name: 'Main',
          component: () => import('../views/main/index.vue'), // 首页
          meta: { title: '首页' }
        },
        {
          path: 'emp',
          name: 'Emp',
          component: () => import('../views/emp/index.vue'),
          meta: { title: '员工管理' }
        },
        {
          path: 'dept',
          name: 'Dept',
          component: () => import('../views/dept/index.vue'),
          meta: { title: '部门管理' }
        },
        {
          path: 'clazz',
          name: 'Clazz',
          component: () => import('../views/clazz/index.vue'),
          meta: { title: '班级管理' }
        },
        {
          path: 'stu',
          name: 'Stu',
          component: () => import('../views/stu/index.vue'),
          meta: { title: '学员管理' }
        },
        {
          path: 'empReport',
          name: 'EmpReport',
          component: () => import('../views/empReport/index.vue'),
          meta: { title: '员工信息统计' }
        },
        {
          path: 'stuReport',
          name: 'StuReport',
          component: () => import('../views/stuReport/index.vue'),
          meta: { title: '学员信息统计' }
        }
      ]
    },
    
    // 添加/index重定向
    {
      path: '/index',
      redirect: '/main'
    }
  ]
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const isAuthenticated = localStorage.getItem('token');
  
  if (to.meta.requiresAuth && !isAuthenticated) {
    next({ name: 'Login' });
  } 
  else if (to.name === 'Login' && isAuthenticated) {
    next({ name: 'Home' }); // 修改为跳转到Home
  } 
  else {
    next();
  }
});

export default router